<?php
namespace app\webadmin\controller;
use think\Cache;
use think\Request;
use think\Db;
class Email extends Base{
    public $reg = [
        '/(@qq.com)$/',
        '/(@163.com)$/',
        '/(@126.com)$/',
        '/(@yeah.net)$/',
        '/(@sina.com)$/',
        '/(@sina.cn)$/',
        '/(@sohu.com)$/',
        '/(@aliyun.com)$/',
        '/(@139.com)$/',
        '/(@189.cn)$/'
    ];
    public $server = [
                '{smtp.qq.com:995/pop3/ssl/novalidate-cert}',
                '{pop.163.com:995/pop3/ssl/novalidate-cert}',
                '{pop.126.com:995/pop3/ssl/novalidate-cert}',
                '{pop.yeah.net:995/pop3/ssl/novalidate-cert}',
                '{pop.sina.com:995/pop3/ssl/novalidate-cert}',
                '{pop.sina.cn:995/pop3/ssl/novalidate-cert}',
                '{pop3.sohu.com:995/pop3/ssl/novalidate-cert}',
                '{pop3.aliyun.com:995/pop3/ssl/novalidate-cert}',
                '{pop.139.com:995/pop3/ssl/novalidate-cert}',
                '{pop.189.cn:995/pop3/ssl/novalidate-cert}'
    ];

    public function authlogin(Request $request){
        $where = [
            'status'=>1,
            'is_delete'=>0
        ];
        $where1 = [
            'channel_identifying'=>1,
            'status'=>2
        ];
        //取出渠道开通的comp_id
        $comp_ids = Db::query("select comp_id from ts_channel_open_info where channel_identifying=1 and status =2");
        foreach($comp_ids as $key=>$val){
            $condition = $val['comp_id'];
            $email = Db::query("select * from ts_channel_open_email_list where comp_id = '{$condition}' and status = 1 and is_delete = 0");
            for($i=0;$i<count($email);$i++){
                print_r($email[$i]['email']);
                // $this->matchSubject($email[$i]['email'],$data[$i]['url'],$data[$i]['auth_code'],$data[$i]['port']);
            }
        }
        // for($i=0;$i<count($data);$i++){
        //     $this->matchSubject($data[$i]['email'],$data[$i]['url'],$data[$i]['auth_code'],$data[$i]['port']);
        // }
    }
    public function matchSubject($email,$serverUrl,$authCode,$port){
        error_reporting(E_ALL ^ E_NOTICE);
        $server = '';
        for ($i=0; $i < count($this->reg) ; $i++) {
            if(preg_match($this->reg[$i],$email)){
                $server = $this->server[$i];
            }
        }
        $mbox = imap_open($server,$email,$authCode);
        // return $mbox;
        if($mbox){
            $reg = '/Subject:(\s?=\S+\?=)+/';
            $reg2 = '/Subject:(\s?\d)+/';
            $totalrows  = imap_num_msg($mbox);
            for ($i=1;$i<=$totalrows;$i++){
                $bodys = imap_fetchheader($mbox,$i); //获取信件标头
                //去掉换行
                $bodys = preg_replace('/\r|\n/', '', $bodys);
                $uniqueID = md5($bodys);
                //匹配邮件标题
                preg_match($reg,$bodys,$res)||preg_match($reg2,$bodys,$res);
                if(isset($res[0])){
                    $rs = $res[0];
                    $rs = str_replace(':=', ': =', $rs);
                    $str = explode(': ', $rs);
                    $title = iconv_mime_decode($str[1]);
                }else{
                    $title = '';
                }
                // print_r($title);
                // $where1 = ['xqq_id' => $uniqueID];
                // $record = Db::name('channel_ticket_log')->where($where1)->select();
                // $sql = "SELECT * from ts_channel_ticket_log WHERE xqq_id = '$uniqueID' limit 1";
                // $record = $this->queryBySql($sql);
                //如果邮件渠道工单记录表没有记录，则发起工单
                // if(count($record)<=0){
                    if($title &&!empty($title)){
                        //去除红点
                        // print_r($title);
                        $title = json_decode(str_replace('\u200b','',json_encode($title)));
                        // $str = json_encode($title);
                        // // print_r($str);
                        // // preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $str, $matches);
                        // $str = str_replace('/\u200b/',',',$str);
                        // // print_r($str);
                        // $title = join('', $matches[0]);
                        // print_r($title);
                        // echo "<br>";
                        $where = [
                            'email_subject'=>$title,
                            'status'=>1,
                        ];
                        // print_r($this->mb_str_split($title));
                        $res = Db::name('channel_strategy_email_list')->where($where)->select();
                        // print_r($res);
                        if($res){
                            print_r($res);
                            // $this->launchWork($res[0],$uniqueID);
                        }
                        // return $email;
                        // $sql = "SELECT * FROM ts_channel_strategy_email_list WHERE email_subject = '$title' limit 1";
                        // $res = $this->queryBySql($sql);
                        // print_r($res);
                        // if($res){
                        //         $this->launchWork($res,$uniqueID);
                        //     }
                    }
                // }
            }
        }
    }
    // public function mb_str_split($str,$split_length=1,$charset="UTF-8"){
    //     if(func_num_args()==1){
    //       return preg_split('/(?<!^)(?!$)/u', $str);
    //     }
    //     if($split_length<1)return false;
    //     $len = mb_strlen($str, $charset);
    //     $arr = array();
    //     for($i=0;$i<$len;$i+=$split_length){
    //       $s = mb_substr($str, $i, $split_length, $charset);
    //       $arr[] = $s;
    //     }
    //     return $arr;
    //   }
    // public function launchWork($workdata,$uniqueID){
    //     // print_r($workdata);
    //     date_default_timezone_set('PRC');
    //     $create_time = date('Y-m-d H:i:s');
    //     $channel_identifying = 1;
    //     // // $this->log('test info',$workdata[0]);
    //     // // $data = $workdata;
    //     $workdataemail = [
    //         'comp_id'     => $workdata['comp_id'],
    //         'template_id' => $workdata['template_id'],
    //         'template_name'=> $workdata['template_name'],
    //         'remark' => '通过【邮件渠道】发起了工单',
    //         'fire_time'=>$create_time
    //     ];
    //     $workrecordemail = [
    //         'comp_id'     => $workdata['comp_id'],
    //         'template_id' => $workdata['template_id'],
    //         'template_name'=> $workdata['template_name'],
    //         'scence_desc' => $workdata['scence_desc'],
    //         'channel_identifying'=>$channel_identifying,
    //         'remark' => '通过【邮件渠道】发起了工单',
    //         'xqq_id'=>$uniqueID,
    //         'create_time'=>$create_time
    //     ];
    //     print_r($workdataemail);
    //     print_r($workrecordemail);
    //     // $launch = $this->insertByTable('ts_ticket_info',$workdata);
    //     // if($launch){
    //     //     $this->insertByTable('ts_channel_ticket_log',$workrecord);
    //     // }
    // }

    public function emailinfo(){
        $server = "{pop.163.com:995/pop3/ssl/novalidate-cert}";
        $userid ="guomei0120@163.com";
        $code = "WIRFWVYXUDNTBEHP";
        // $userid ="1109984533@qq.com";
        // $code = "trdmarwqeeejihig";

        // $userid ="wuyunhao522628@163.com";
        // $code = "NBXNZKSFYUOYGZEK";

        // $userid ="hao522628@163.com";
        // $code = "HXOJLTOJLABCWAVJ";

        // $userid ="haoyunwu522628@163.com";
        // $code = "ZSQOYHVJBHMIIHXE";

        // $userid ="cj522628@163.com";
        // $code = "HBYBJERFJOVPDHNI";
        $mbox = imap_open($server, $userid, $code) or die(imap_last_error());
        $totalrows = imap_num_msg($mbox);
        $reg = '/Subject:(\s?=\S+\?=)+/';
        $reg2 = '/Subject:(\s?\d)+/';
        for ($i = 1; $i <=$totalrows; $i++) {
                $bodys = imap_fetchheader($mbox,$i); //获取信件标头
                $bodys = preg_replace('/\r|\n/', '', $bodys);
                // print_r($bodys);
                preg_match($reg,$bodys,$res)||preg_match($reg2,$bodys,$res);
                print_r($res);
                if(isset($res[0])){
                    $rs = $res[0];
                    $rs = str_replace(':=', ': =', $rs);
                    $str = explode(': ', $rs);
                    $title = iconv_mime_decode($str[1]);
                }else{
                    $title = '';
                }

                $data = [
                    'title'=>$title,
                    'messageID'=>md5($bodys)
                ];
                print_r($data);
                echo "<hr>";
        }
    }
    public function str(){
        // $str1 = "​回你一条信息标题";
        // echo json_encode($str1);
        // $str1 = json_decode(str_replace('\u200b','',json_encode($str1)));
        // echo $str1;
        $server = "smtp.qq.com:995/pop3/ssl";
        $serverUrl = "{{$server}}";
        echo $serverUrl;
    }

    public function posts(){
        // $url = "http://112.74.161.13:53025/v1/api/getMsgType";
        // $curl = curl_init();
        // //设置抓取的url
        // curl_setopt($curl, CURLOPT_URL,$url);
        // //设置头文件的信息作为数据流输出
        // curl_setopt($curl, CURLOPT_HEADER, 1);
        // //设置获取的信息以文件流的形式返回，而不是直接输出。
        // curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // //设置post方式提交
        // curl_setopt($curl, CURLOPT_POST, 1);
        // //设置post数据
        // $post_data = array();
        // //post提交的数据
        // curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        // //执行命令
        // $data = curl_exec($curl);
        // //关闭URL请求
        // curl_close($curl);
        // //显示获得的数据
        // $str = '{"status":true,"content":"{\"code\":0,\"ticket_id\":\"90037b1643692e48e851b15572165ca3\",\"msg\":\"success\",\"url\":\"http:\\\/\\\/112.74.161.13:53035\\\/ticket\\\/process\\\/index?ticket_id=90037b1643692e48e851b15572165ca3\"}","code":200}
        // ';
        // $str = json_decode($str,true);
        // $content = $str['content'];
        // $contents = json_decode($content,true);
        // $ticket_id = $contents['ticket_id'];
        // $msg = $contents['msg'];
        // print_r($ticket_id);
        // print_r($msg);
        $str = '{"status":true,"content":"{\"code\":0,\"ticket_id\":\"d67c9098f2f1c0e2f3765ecade69a420\",\"msg\":\"success\",\"url\":\"http:\\\/\\\/112.74.161.13:53035\\\/ticket\\\/process\\\/index?ticket_id=d67c9098f2f1c0e2f3765ecade69a420\"}","code":200}
        ';
        print_r(json_decode($str,true));
    }
}